package com.kma.summer2012.client.presenters.manager;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.DialogBoxFactory;
import com.kma.summer2012.client.events.manager.AddWorkCategoryEvent;
import com.kma.summer2012.client.events.manager.AddWorkEvent;
import com.kma.summer2012.client.events.manager.EditWorkCategoryEvent;
import com.kma.summer2012.client.events.manager.EditWorkEvent;
import com.kma.summer2012.client.events.request.MainPageEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.catalogOfWorks.CrumbsCatalogOfWorksService;
import com.kma.summer2012.client.view.PopUpPreloader;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.widgets.events.DoubleClickEvent;
import com.smartgwt.client.widgets.events.DoubleClickHandler;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: Администратор
 * Date: 12.02.13
 * Time: 20:05
 * To change this template use File | Settings | File Templates.
 */
public class ManageWorksPresenter implements Presenter {

    public interface Display {
        TreeGrid getTreeGrid();

        HasClickHandlers getAddWorkButton();

        HasClickHandlers getAddCategoryButton();

        HasClickHandlers getDeleteWorkButton();

        HasClickHandlers getBackButton();

        HasClickHandlers getEditButton();

        public void setEditEnable(boolean enable);

        public void setDelEnable(boolean enable);

        Widget asWidget();

    }

    private final Display display;

    public ManageWorksPresenter(Display display) {
        this.display = display;
        fillCatalog();
        bind();
    }

    public void fillCatalog() {
        CrumbsCatalogOfWorksService.App.getInstance().getAllWorks(new AbstractCallBack<Set<UICrumbsWorkItem>>() {
            @Override
            public void onSuccess(Set<UICrumbsWorkItem> result) {
                TreeGridField workField = new TreeGridField("Work");
                TreeGridField workDescriptionField = new TreeGridField("WorkDescription");
                TreeGridField runTimeField = new TreeGridField("RunTime");
                TreeGridField toolsField = new TreeGridField("Tools");
                ManageWorksPresenter.this.display.getTreeGrid().setFields(workField, workDescriptionField, runTimeField, toolsField);


                final Tree tree = new Tree();

                tree.setModelType(TreeModelType.PARENT);
                tree.setNameProperty("Work");
                tree.setIdField("Id");
                tree.setParentIdField("ReportsTo");
                tree.setShowRoot(false);

                TreeNode[] treeNodes = new TreeNode[result.size()];
                int i = 0;
                for (UICrumbsWorkItem item : result) {

                    int parentId;
                    if (item.isParent())
                        if (item.getParentId() == 0) {
                            parentId = 0;
                        } else parentId = item.getParentId();
                    else parentId = item.getParentId();
                    String tools = "";
                    if (item.getToolList() != null) {
                        for (String tool : item.getToolList()) {
                            tools += tool + "; ";
                        }
                    }
                    int runtime;
                    if (item.getRuntime() != null) {
                        runtime = item.getRuntime();
                        treeNodes[i] = new TreeGridNode(item.getId(),
                                parentId,
                                item.getWorkName(),
                                item.getWorkDescription(),
                                runtime,
                                item.isParent(),
                                tools
                        );
                    } else {
                        treeNodes[i] = new TreeGridNode(item.getId(),
                                parentId,
                                item.getWorkName(),
                                item.getWorkDescription(),
                                "",
                                item.isParent(),
                                tools
                        );
                        final String bUrl = GWT.getModuleBaseURL() + "/sc/skins/Enterprise/images/FileBrowser/folder.png";
                        treeNodes[i].setIcon(bUrl);
                    }
                    i++;
                }

                tree.setData(treeNodes);
                ManageWorksPresenter.this.display.getTreeGrid().setData(tree);
                ManageWorksPresenter.this.display.getTreeGrid().addDrawHandler(new DrawHandler() {
                    public void onDraw(DrawEvent event) {
                        tree.openAll();

                    }
                });
                ManageWorksPresenter.this.display.getTreeGrid().setSortField(1);
                ManageWorksPresenter.this.display.getTreeGrid().sort();
            }
        });
    }

    private void bind() {

        this.display.getAddWorkButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doAddWork();
            }
        });

        this.display.getAddCategoryButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doAddWorkCategory();
            }
        });

        this.display.getDeleteWorkButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                List<HasClickHandlers> list = new ArrayList<HasClickHandlers>();
                list.add(new Button("Delete", new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent clickEvent) {
                        doDeleteWorks();//To change body of implemented methods use File | Settings | File Templates.
                    }
                }));
                DialogBoxFactory.createMessageBox("Do you really want to delete this work?", "O'RLY?", list).show();
            }
        });

        this.display.getBackButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
            }
        });
        this.display.getTreeGrid().addSelectionChangedHandler(new SelectionChangedHandler() {
            @Override
            public void onSelectionChanged(SelectionEvent selectionEvent) {
                ListGridRecord[] listGridRecords = ManageWorksPresenter.this.display.getTreeGrid().getSelectedRecords(true);
                if (listGridRecords == null || listGridRecords.length == 0) {
                    ManageWorksPresenter.this.display.setDelEnable(false);
                    ManageWorksPresenter.this.display.setEditEnable(false);
                } else {
                    if (listGridRecords.length == 1) {
                        ManageWorksPresenter.this.display.setDelEnable(true);
                        ManageWorksPresenter.this.display.setEditEnable(true);
                    } else {
                        ManageWorksPresenter.this.display.setDelEnable(true);
                        ManageWorksPresenter.this.display.setEditEnable(false);
                    }
                }
            }
        });
        this.display.getTreeGrid().addDoubleClickHandler(new DoubleClickHandler() {
            @Override
            public void onDoubleClick(DoubleClickEvent doubleClickEvent) {
                ListGridRecord record = ManageWorksPresenter.this.display.getTreeGrid().getSelectedRecord();

                if (record != null) {
                    doEdit(record);
                }
            }
        });
        this.display.getEditButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                ListGridRecord record = ManageWorksPresenter.this.display.getTreeGrid().getSelectedRecord();
                if (record != null) {
                    doEdit(record);
                }
            }
        });

    }

    private void doEdit(ListGridRecord record) {
        if (record.getAttributeAsBoolean("IsParent") == false) {
            int id = record.getAttributeAsInt("Id");
            CrumbsCatalogOfWorksService.App.getInstance().getWorkById(id, new AbstractCallBack<UICrumbsWorkItem>(){
                @Override
                public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                    CrumbsEventBus.getInstance().fireEvent(new EditWorkEvent(uiCrumbsWorkItem));
                }
            });
        } else {
            int id = record.getAttributeAsInt("Id");
            CrumbsCatalogOfWorksService.App.getInstance().getWorkById(id, new AbstractCallBack<UICrumbsWorkItem>() {
                @Override
                public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                    CrumbsEventBus.getInstance().fireEvent(new EditWorkCategoryEvent(uiCrumbsWorkItem));
                }
            });
        }
    }

    private void doDeleteWorks() {
        PopUpPreloader.show();
        ListGridRecord[] listGridRecords = ManageWorksPresenter.this.display.getTreeGrid().getSelectedRecords(true);
        ArrayList<Integer> idList = new ArrayList<Integer>();
        for (int i = 0; i < listGridRecords.length; i++) {
            final ListGridRecord record = listGridRecords[i];
            //String workName = record.getAttributeAsString("work");     //?
            if (record.getAttributeAsBoolean("isParent")) {
                Boolean answer = true;
                if (!answer) continue;
            }
            idList.add(record.getAttributeAsInt("Id"));
        }
        //Перевіряє ворки і категорії в фасаді
        CrumbsCatalogOfWorksService.App.getInstance().deleteAllWorks(idList, new AbstractCallBack<Boolean>() {
           @Override
            public void onSuccess(Boolean allDeleted) {
                PopUpPreloader.hide();
                if (!allDeleted) {
                    Window.alert("Some works couldn't be deleted because they are being processed in requests!");
                }
                fillCatalog();
            }
        });
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

    private void doAddWorkCategory() {

        UICrumbsWorkItem newUiWork = new UICrumbsWorkItem();
        CrumbsEventBus.getInstance().fireEvent(new AddWorkCategoryEvent(newUiWork));

    }

    void doAddWork() {

        UICrumbsWorkItem newUiWork = new UICrumbsWorkItem();
        CrumbsEventBus.getInstance().fireEvent(new AddWorkEvent(newUiWork));

    }

    private static class TreeGridNode extends TreeNode {

        public TreeGridNode(int id, int reportsTo, String name, String description, int runTime, boolean isParent, String tools) {
            setId(id);
            setReportsTo(reportsTo);
            setName(name);
            setDescription(description);
            setRunTime(runTime);
            setIsParent(isParent);
            setTools(tools);
        }

        public TreeGridNode(int id, int reportsTo, String name, String description, String runTime, boolean isParent, String tools) {
            setId(id);
            setReportsTo(reportsTo);
            setName(name);
            setDescription(description);
            setRunTime(runTime);
            setIsParent(isParent);
            setTools(tools);
        }

        public void setId(int value) {
            setAttribute("Id", value);
        }

        public void setDescription(String value) {
            setAttribute("WorkDescription", value);

        }

        public void setReportsTo(int value) {
            setAttribute("ReportsTo", value);
        }

        public void setName(String name) {
            setAttribute("Work", name);
        }

        public void setRunTime(int runTime) {
            setAttribute("RunTime", runTime);
        }

        public void setRunTime(String runTime) {
            setAttribute("RunTime", runTime);
        }

        public void setIsParent(boolean isParent) {
            setAttribute("IsParent", isParent);
        }

        public void setTools(String tools) {
            setAttribute("Tools", tools);
        }
    }
}
